package top.jacktgq.itheima.netty.protocol_design.groupchat.message;

import io.netty.channel.ChannelHandlerContext;
import lombok.Data;
import lombok.ToString;
import top.jacktgq.itheima.netty.protocol_design.groupchat.server.session.GroupSessionFactory;

import java.util.Set;

@Data
@ToString(callSuper = true)
public class GroupJoinRequestMessage extends Message {
    private String groupName;

    private String username;

    public GroupJoinRequestMessage() {
    }

    public GroupJoinRequestMessage(String username, String groupName) {
        this.groupName = groupName;
        this.username = username;
    }

    @Override
    public int getMessageType() {
        return GroupJoinRequestMessage;
    }

    @Override
    public void handle(ChannelHandlerContext ctx) {
        Set<String> members = GroupSessionFactory.getGroupSession().getMembers(groupName);
        GroupJoinResponseMessage message = null;
        if (members.size() > 0) {
            // 检查用户是否已经在群中
            if (members.contains(username)) {
                message = new GroupJoinResponseMessage(false, "您已在群 " + groupName + " 中，请勿重复加群");
            } else {
                members.add(username);
                message = new GroupJoinResponseMessage(true, "你已成功加入群 " + groupName);
            }
        } else {
            // 群不存在
            message = new GroupJoinResponseMessage(false, "您要加入的群 " + groupName + " 不存在");
        }
        ctx.writeAndFlush(message);
    }
}
